<?php

namespace Frieza\Modules\Comment\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\LegoCounter;
use Doraemon\cache\Queue;
use Doraemon\model\Comment as dbComment;
use Doraemon\model\CommentActivity as DbCommentActivity;
use Doraemon\model\CommentMasterStat;
use Doraemon\model\Es\Comment;
use Doraemon\model\Member;
use Doraemon\pockets\excel\DownExcel;
use Doraemon\service\User;
use Doraemon\tools\Filter;
use Doraemon\tools\Hhzurl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Frieza\Modules\Comment\Actions\BatchUpdateStatus;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;


class CommentActivityController extends Controller
{

    private $comment_status_map = [
        DbCommentActivity::STATUS_NORMAL => '精选',
        DbCommentActivity::STATUS_DEL => '已删除',
        DbCommentActivity::STATUS_NOT => '未审核',
    ];

    private $comment_top_map = [
        30 => '无置顶',
        1 => 1,
        2 => 2,
        3 => 3,
        4 => 4,
        5 => 5,
    ];


    public function index(Request $request, Content $content)
    {
        $tab = new tab();
        $title = '活动页评论列表';

        $tab->add($title, $this->listData($request));

        return $content
            ->header('评论管理')
            ->breadcrumb(
                ['text' => $title]
            )
            ->body($tab);
    }


    private function listData(Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $search = $request->input('search', []);
        $query = [];
        if (isset($search['uid']) && is_numeric($search['uid'])) {
            $query['uid'] = $search['uid'];
        }
//        if (!empty($search['activity_id'])) {
//            $query['activity_id'] = $search['activity_id'];
//        }

//        if (!empty($search['content'])) {
//            $query['content[~]'] = $search['content'];
//        }
        if (!empty($search['obj_id'])) {
            $query['obj_id'] = $search['obj_id'];
        }

        if (!empty($search['content'])) {
            $query['content'] = $search['content'];
        }

        if (!empty($search['status'])) {
            $query['status'] = 1;
        }

        $query['obj_type'] = \Doraemon\model\Comment::LEGO_COMMENT_TYPE;

        $export = $query;
        $export['page'] = $page;
        $export['page_size'] = $pageSize;
        $export_url = http_build_query($export);
        $comment_data = $this->getAcitvityCommentData($query, $page, $pageSize);
        $gridModel = new pGridDataModel($comment_data['data'], $comment_data['total'], ['perPage' => $pageSize, '']);

        $gridModel->setKeyType('string');
        $gridModel->setKeyName("new_id");
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $search, $export_url) {
            $grid->disableExport();
//            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->paginate($gridModel->getPerPage());
            $grid->tools(function ($tools) use ($export_url) {
                $tools->append(<<<HTML
<a class="btn button-success" href="/admin/comment/activity/index/export?{$export_url}">
    <i class="fa fa-download"/> 导出
</a>
HTML
                );
            });
            //筛选
            $grid->filter(function (Grid\Filter $filter) use ($search) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.uid', 'uid')->integer()->default($search['uid']);
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.obj_id', '活动页ID')->default($search['obj_id']);
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->equal('search.content', '关键字')->default($search['content']);
                });


                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
                    $filter->in('search.status', "精选")->checkbox([
                        '1'    => '',
                    ])->default($search['status']);
                });

                //条件展开
                if ($search) $filter->expand();
            });

            $grid->column('id');
            $grid->column('uid', '用户信息')->userBasicInfo();
            $grid->column('obj_id', '活动页ID');
            $grid->column('to_uid', 'to用户')->display(function ($uid){
                $userInfo = User::getUser($uid);
                return $userInfo['nick'] ? : '';
            });
            $grid->column('content', '内容');
            $grid->column('addtime', '评论时间')->display(function ($addtime) {
                return date("Y-m-d H:i:s", $addtime);
            });
            $grid->column('status', '状态')->using($this->comment_status_map);
            $grid->column('like_num', '点赞数')->display(function (){
                $hot_text = ($this->like_num >= 3) ? "热门" : "";
                return $this->like_num . "|" . $hot_text;
            });
            $grid->column('top_level','置顶')->using($this->comment_top_map, "无置顶");

            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                    $batch->add('批量精选', new BatchUpdateStatus(1));
                    $batch->add('批量取消精选', new BatchUpdateStatus(0));
                });
            });
            Admin::script($this->setScript());

            $grid->actions(function ($actions) {
                $option = [
                    30 => "无置顶",
                    1 => 1,
                    2 => 2,
                    3 => 3,
                    4 => 4,
                    5 => 5,
                    //30 => '无置顶',
                ];
                $optionStr = '';
                foreach ($option as $key => $val) {
                    if ($actions->row->top_level == $key) {
                        $optionStr.= '<option value="'.$key.'" selected> '.$val.'</option>';
                    } else {
                        $optionStr.= '<option value="'.$key.'"> '.$val.'</option>';
                    }
                }

                if ($actions->row->status == dbComment::STATUS_NOT) { //未精选不能操作置顶所以置灰
                    $actions->prepend(
                        '<p>置顶<select class="zd" id="'. $actions->row->id .'" disabled>
"'. $optionStr .'"
                            </select>
                            </p>'
                    );
                } else {
                    $actions->prepend(
                        '<p>置顶<select class="zd" id="'. $actions->row->id .'">
"'. $optionStr .'"
                            </select>
                            <a class="setTop label  label-info" data-id="' . $actions->row->id . '" data-new-id="' . $actions->row->new_id . '" data-top="' . $actions->row->top_level . '" href="javascript:void(0);">提交</a>
                            </p>'
                    );
                }

                if ($actions->row->status == DbCommentActivity::STATUS_NOT) {
                    $actions->prepend('<p><a href="/admin/comment/activity/index/set/' . $actions->row->new_id . '/'.DbCommentActivity::STATUS_NORMAL.'" >精选</a></p>');
                }
                if ($actions->row->status == DbCommentActivity::STATUS_NORMAL) {
                    $actions->prepend('<p><a href="/admin/comment/activity/index/set/' . $actions->row->new_id . '/'.DbCommentActivity::STATUS_NOT.'" >取消精选</a></p>');
                }

                $actions->disableEdit();
                $actions->disableView();
                $actions->disableDelete();
            });
        });

        return $listGrid->render();

    }

    private function getAcitvityCommentData($query, $page, $pageSize)
    {

//        $comment_data = [
//            "data" => [],
//            "total" => 0
//        ];
//
//        $comment_list = sLegoComment::getAdminList($query, $page, $pageSize);
//
//        if ($comment_list && is_array($comment_list)){
//            $count = sLegoComment::getCountByWhere($query);
//            $comment_data = [
//                "total" => $count,
//                "data" => $comment_list
//            ];
//        }
//        return $comment_data;
//        return [
//            "data" => [
//                [
//                    'new_id' => '10010:101:23333533',
//                    'id'=> 23333533,
//                    'uid' => 23333508,
//                    'to_uid' => 0,
//                    'content' => '欢迎光临',
//                    'addtime' => 1668070736,
//                    'obj_id' => 10010,
//                    'obj_type' => 101,
//                    'status' => 1,
//                    'top_level' => 2,
//                    'like_num' => 2
//                ],
//                [
//                    'new_id' => '10010:101:23333534',
//                    'id'=> 23333534,
//                    'uid' => 23333508,
//                    'to_uid' => 23333508,
//                    'content' => '欢迎光临12',
//                    'addtime' => 1668070958,
//                    'obj_id' => 10010,
//                    'obj_type' => 101,
//                    'status' => 1,
//                    'top_level' => 30,
//                    'like_num' => 3
//                ]
//            ],
//            "total" => 2
//        ];
        $comment_data = [
            "data" => [],
            "total" => 0
        ];

        $comment_list = Comment::search($query, $page, $pageSize);
        if ($comment_list && is_array($comment_list)){
            $comment_data = [
                "total" => $comment_list['total'],
                "data" => $comment_list['rows']
            ];
        }
        return $comment_data;
    }

    public function setStaus($id, $status)
    {
        if (!in_array($status, [dbComment::STATUS_NOT, dbComment::STATUS_NORMAL])) {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }

        $data['status'] = $status;
        $data['admin_id'] = Admin::user()->id ?? 0;
        if ($status == dbComment::STATUS_NOT) { //取消精选自动取消其置顶状态
            $data['top_level'] = dbComment::DEFAULT_TOP_LEVEL;
        }

        $str = explode(':', $id);

        $objId = $str[0] ?? 0;
        $objType = $str[1] ?? 0;
        $cmtId = $str[2] ?? 0;

        if (!$objId || !$objType || !$cmtId) {
            $result = ['status' => 0, 'message' => '评论数据错误'];
            return response()->json($result);
        }
//        dd($data);
//        $rs = DbCommentActivity::update($data, ['id' => $id]);
        $rs = dbComment::update($data, ['id' => $cmtId, 'obj_id' => $objId, 'obj_type' => $objType]);
        unset($data['admin_id']);
        if ($rs) {
            $cacheId = $objId.':'.$objType;
            if ($status == dbComment::STATUS_NOT) { //未精选相当于未审核 减去计数器
                $del_count = -1;
                if( isset($commentInfo['type'])&& $commentInfo['type'] == 1){
                    $sub_count = (int) dbComment::getSubCount($objId, [$cmtId], $objType) ? : 0;
                    $del_count -= $sub_count;
                }

                LegoCounter::decreaseLegoCounter($cacheId, LegoCounter::ACT_COMMENT);
                LegoCounter::decreaseLegoCounter($cacheId, LegoCounter::ACT_MASTER_COMMENT, $del_count);
            } else { //精选相当于审核 加上计数器
                $add_count = 1;
                if( isset($commentInfo['type'])&& $commentInfo['type'] == 1){
                    $sub_count = (int) dbComment::getSubCount($objId, [$cmtId], $objType) ? : 0;
                    $add_count += $sub_count;
                }

                LegoCounter::increaseLegoCounter($cacheId, LegoCounter::ACT_COMMENT);
                LegoCounter::increaseLegoCounter($cacheId, LegoCounter::ACT_MASTER_COMMENT, $add_count);
            }
            //同步es
            $data['id'] = $cmtId;
            \Doraemon\cache\Queue::insertQueue("queue/es/commentpost", array(
                "new_id" => $id,
                "field" => json_encode($data)
            ), \Doraemon\cache\Queue::QUEUE_ES_SYNC);

            // 发通知
            if ($status == dbComment::STATUS_NORMAL) {
                $info = dbComment::get('*', ['id' => $cmtId, 'obj_id' => $objId, 'obj_type' => $objType]);
                $msgData =  [
                    'msgCode' => 760,
                    'to_uid' => $info['uid'],
                    'msgParams' => [
                        'link' => 'niceliving://webview/normalscreen?protego=' . urlencode(base64_encode(json_encode(['url' => Hhzurl::getLeGo($info['obj_id'])]))),
                    ]
                ];
                \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', $msgData, \Doraemon\cache\Queue::QUEUE_DORAEMON);
            }
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            sleep(1);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public function setTop($id, Request $request)
    {
        $top = $request->post('is_top');
        $oldTop = $request->post('old_top');
        $newId = $request->post('new_id');

        if ($top == $oldTop) {
            $result = ['status' => 1, 'message' => '操作成功'];
            return response()->json($result);
        }

        $str = explode(':', $newId);
        $objId = $str[0] ?? 0;
        $objType = $str[1] ?? 0;
        $cmtId = $str[2] ?? 0;

        if (!$objId || !$objType || !$cmtId) {
            $result = ['status' => 0, 'message' => '评论数据错误'];
            return response()->json($result);
        }

        $where = [
            'obj_id' => $objId,
            'obj_type' => $objType
        ];
        //无置顶状态外1个活动每个置顶纬度只能有一条数据
        if ($top != dbComment::DEFAULT_TOP_LEVEL) {

            $iCommentId = dbComment::get('id', ['obj_id' => $objId, 'obj_type' => $objType, 'top_level' => $top]);
//            $aCommentId = DbCommentActivity::get('id', ['activity_id' => $activityId, 'top_level' => $top]);

            if ($iCommentId) {
//                $oldRs = DbCommentActivity::update(['top_level' => 30], ['id' => $commentId]);
                $where['id'] = $iCommentId;
                $oldRs =  dbComment::update(['top_level' => dbComment::DEFAULT_TOP_LEVEL, 'admin_id' => Admin::user()->id ?? 0], $where);

                if ($oldRs !== true) {
                    $result = ['status' => 0, 'message' => '操作失败'];
                    return response()->json($result);
                }
                //更新统计表
                CommentMasterStat::update(['top_level' => dbComment::DEFAULT_TOP_LEVEL], ['obj_id' => $objId,  'obj_type' => $objType, 'origin_id' => $iCommentId]);
                //更新Es
                $oldNewId = $objId.':'.$objType.':'.$iCommentId;

                $oSyncEsData = [
                    'id' => $iCommentId,
                    'top_level' => dbComment::DEFAULT_TOP_LEVEL
                ];
                \Doraemon\cache\Queue::insertQueue("queue/es/commentpost", array(
                    "new_id" => $oldNewId,
                    "field" => json_encode($oSyncEsData)
                ), \Doraemon\cache\Queue::QUEUE_ES_SYNC);
            }
        }

        $data['top_level'] = $top;
        $data['admin_id'] = Admin::user()->id ?? 0;
        $where['id'] = $cmtId;
        $rs = dbComment::update($data, $where);
        unset($data['admin_id']);
        if (!$rs) {
            $result = ['status' => 0, 'message' => '操作失败'];
            return response()->json($result);
        }
        CommentMasterStat::update($data, ['obj_id' => $objId,  'obj_type' => $objType, 'origin_id' => $cmtId]);
        //更新Es
        $SyncEsData = [
            'id' => $cmtId,
            'top_level' => $top
        ];

        \Doraemon\cache\Queue::insertQueue("queue/es/commentpost", array(
            "new_id" => $newId,
            "field" => json_encode($SyncEsData)
        ), \Doraemon\cache\Queue::QUEUE_ES_SYNC);
        $result = ['status' => 1, 'message' => '操作成功'];
        sleep(1);
        return response()->json($result);

    }

    private function setScript()
    {
        return <<<SCRIPT
         $('.zd').change(function () {
              var change_top = $(this).val()
              $(this).attr("value", change_top)
         })
           
        $('.setTop').unbind('click').click(function(){
            var id = $(this).attr('data-id');
            var old_top = $(this).attr('data-top');
            var new_id = $(this).attr('data-new-id');
            var is_top = $(this).prev().val();
            let that = $(this)
            let url = '/admin/comment/activity/index/setTop/'+ id;
            let params = {
                is_top:is_top,
                old_top:old_top,
                new_id:new_id,
            };
            $.post(url, params , function (result) {                
                if (result.status == 1) {
                    layer.msg(result.message); 
                    window.location.reload();                               
                } else {
                    layer.msg(result.message);
                }
            });
        });
        SCRIPT;
    }

    public function batchSetStatus(Request $request)
    {
        $newIds = $request->get('ids');
        $status = $request->get('status');
//        $newIds = [
//          "10010:101:23333533",
////          "4:101:3",
////          "4:101:2",
////          "4:101:1",
//        ];
        $whereStatus = $status == dbComment::STATUS_NORMAL ? dbComment::STATUS_NOT : dbComment::STATUS_NORMAL;
        foreach ($newIds as $newId) {
            $str = explode(':', $newId);
            $objId = $str[0] ?? 0;
            $objType = $str[1] ?? 0;
            $cmtId = $str[2] ?? 0;

            if (!$objId || !$objType || !$cmtId) {
                $result = ['status' => 0, 'message' => '评论id错误'];
                return response()->json($result);
            }

            $commentInfo = dbComment::getCommentById($cmtId, $objId, $whereStatus, $objType);

            if (empty($commentInfo)) {
                $result = ['status' => 0, 'message' => '评论数据不存在'];
                return response()->json($result);
            }
            $data['status'] = $status;
            $data['admin_id'] = Admin::user()->id ?? 0;
            if ($status == dbComment::STATUS_NOT) { //取消精选自动取消其置顶状态
                $data['top_level'] = dbComment::DEFAULT_TOP_LEVEL;
                $syncEsData['top_level'] = dbComment::DEFAULT_TOP_LEVEL;
            }
            $res = dbComment::update($data, ['id' => $cmtId, 'obj_id' => $objId, 'obj_type' => $objType]);

            if (!$res) {
                $result = ['status' => 0, 'message' => '评论数据操作失败'];
                return response()->json($result);
            }

            $new_id = $objId.':'.$objType.':'.$cmtId;
            $syncEsData['id'] = $cmtId;
            $syncEsData['status'] = $status;

            $cacheId = $objId.':'.$objType;
            if ($status == dbComment::STATUS_NOT) { //未精选相当于未审核 减去计数器
                $del_count = -1;
                if( isset($commentInfo['type'])&& $commentInfo['type'] == 1){
                    $sub_count = (int) dbComment::getSubCount($objId, [$cmtId], $objType) ? : 0;
                    $del_count -= $sub_count;
                }

                LegoCounter::decreaseLegoCounter($cacheId, LegoCounter::ACT_COMMENT);
                LegoCounter::decreaseLegoCounter($cacheId, LegoCounter::ACT_MASTER_COMMENT, $del_count);
            } else { //精选相当于审核 加上计数器
                $add_count = 1;
                if(isset($commentInfo['type']) && $commentInfo['type'] == 1){
                    $sub_count = (int) dbComment::getSubCount($objId, [$cmtId], $objType) ? : 0;
                    $add_count += $sub_count;
                }

                LegoCounter::increaseLegoCounter($cacheId, LegoCounter::ACT_COMMENT);
                LegoCounter::increaseLegoCounter($cacheId, LegoCounter::ACT_MASTER_COMMENT, $add_count);

                $msgData =  [
                    'msgCode' => 760,
                    'to_uid' => $commentInfo['uid'],
                    'msgParams' => [
                        'link' => 'niceliving://webview/normalscreen?protego=' . urlencode(base64_encode(json_encode(['url' => Hhzurl::getLeGo($commentInfo['obj_id'])]))),
                    ]
                ];
                \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', $msgData, \Doraemon\cache\Queue::QUEUE_DORAEMON);
            }
            //更新Es
            \Doraemon\cache\Queue::insertQueue("queue/es/commentpost", array(
                "new_id" => $new_id,
                "field" => json_encode($syncEsData)
            ), \Doraemon\cache\Queue::QUEUE_ES_SYNC);
        }
        sleep(1);
        $result = ['status' => 1, 'message' => '操作成功'];
        return response()->json($result);
    }

    public function export(Request $request)
    {
        $query = $request->all();
        $page = $query['page'] ?? 1;
        $pageSize = $query['page_size'] ?? 1;
        unset($query['page']);
        unset($query['page_size']);
        unset($query['_pjax']);

        $comment_data = $this->getAcitvityCommentData($query, $page, $pageSize);
        $exportData = $comment_data['data'];
        if (empty($exportData)) {
            $result = ['status' => 1, 'message' => '暂无数据可以导出'];
            return response()->json($result);
        }

        $downExcel = new DownExcel();
        $title = "乐高评论数据";
        $downExcel->setFrontBold('1');
        $downExcel->setFileName($title);
        $downExcel->setTitle($title);
        $downExcel->setSheetTitle($title);
        $widths = [
            'A' => 10,
            'B' => 15,
            'C' => 20,
            'D' => 15,
            'E' => 15,
            'F' => 20,
            'G' => 50,
            'H' => 15,
            'I' => 15,
            'J' => 15,
            'K' => 15,
        ];
        $downExcel->setWidth($widths);
        $head = [
            'ID',
            'UID',
            '用户昵称',
            '用户身份',
            '活动页ID',
            'to用户',
            '内容',
            '评论时间',
            '状态',
            '点赞数',
            '置顶',
        ];
        foreach ($exportData as $row) {
            $userinfo = User::getBasicUserInfoByCache($row['uid']);
            $toUser = [];
            if ($row['to_uid']) {
                $toUser = User::getBasicUserInfoByCache($row['to_uid']);
            }
            $data[] = [
                $row['id'],
                $row['uid'],
                $userinfo['nick'] ?? "",
                Member::$typeDesc[$userinfo['type']??0],
                $row['obj_id'],
                $toUser['nick'] ?? "",
                $row['content'] ? self::filterEmoji($row['content']): "",
                date('Y-m-d H:i:s', $row['addtime']),
                $this->comment_status_map[$row['status']] ?? '',
                $row['like_num'],
                $this->comment_top_map[$row['top_level']] ?? '无置顶'
            ];
        }

        $downExcel->create($data, $head);
        return back();

    }

    private static function filterEmoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }
}